#!/usr/bin/python2.7
# -*- coding:UTF-8 -*-

import os
import stat # 权限
import shutil
import zipfile



def unzip_file(zip_path = '', dir_path = ''):
    '文件解压操作'
    if zipfile.is_zipfile(zip_path):
        print ' 开始解包 '.center(80, '*')
        fz = zipfile.ZipFile(zip_path, 'r')
        for file in fz.namelist():
            # 指定解压路径
            fz.extract(file, dir_path)
            # 设置文件权限
            os.chmod(os.path.join(dir_path, file), stat.S_IRWXU)
            print '解包:', file
        print ' 解包完成 '.center(80, '*')
        fz.close()
    else:
        print '***解包失败***'



def zip_file(dir_path = '', zip_path = ''):
    '文件压缩操作'
    if len(dir_path) and len(zip_path):
        print ' 开始打包 '.center(80, '*')
        fz = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED)
        for path, dirnames, filenames in os.walk(dir_path):
            # 可以去掉根目录打包
            fpath = path.replace(dir_path, '')
            for filename in filenames:
                print '打包:', os.path.join(path, filename)
                fz.write(os.path.join(path, filename), os.path.join(path, filename))
        fz.close()
        print ' 打包完成 '.center(80, '*')
    else:
        print '***打包失败***'



def move_files(old_path, new_path, flags = '-'):
    '文件或目录移动操作'
    # 判断路径是否存在
    if os.path.exists(old_path) and os.path.exists(new_path):
        pass
    else:
        print '[ move_files ]:移动路径错误:old = %s, new = %s' % (old_path, new_path)
        return
    # 判断移动的是文件还是文件夹
    if  os.path.isfile(old_path):
        # 移动文件
        shutil.move(old_path, new_path)
    else:
        # 遍历移动文件夹的内容
        fileList = os.listdir(old_path)
        for i in range(len(fileList)):
            # 判断文件是否存在
            if os.path.exists(os.path.join(new_path, fileList[i])):
                if flags == '-n':
                    # flags = -n :同名的不移动
                    continue
                else:
                    # flags != -n :同名的,先删除,再移动
                    if os.path.isfile(os.path.join(new_path, fileList[i])):
                        # 文件删除
                        os.remove(os.path.join(new_path, fileList[i]))
                    else:
                        # 目录删除
                        shutil.rmtree(os.path.join(new_path, fileList[i]))
                    # 移动
                    shutil.move(os.path.join(old_path, fileList[i]), os.path.join(new_path, fileList[i]))
            else:
                shutil.move(os.path.join(old_path, fileList[i]), os.path.join(new_path, fileList[i]))



def change_symbol(old_symbol = '', flag = '+'):
    '字符串特殊符转义替换'
    if flag == '+':
        old_symbol = old_symbol.replace('(', '\(')
        old_symbol = old_symbol.replace(')', '\)')
    elif flag == '-':
        old_symbol = old_symbol.replace('\(', '(')
        old_symbol = old_symbol.replace('\)', ')')
        old_symbol = old_symbol.replace('\&', '&')

    return old_symbol
